package com.atguigu.day03;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

//100个线程，每个线程加100次，求最后的number值
public class CASDemo2 {
    //V1 多线程环境下不使用原子类AtomicInteger保证线程安全
    private int number=0;
    public int getNumber() {
        return number;
    }
    public synchronized void setNumber() {
        number++;
    }
    //V2 多线程环境下使用原子类AtomicInteger保证线程安全

    AtomicInteger atomicInteger =  new AtomicInteger(0);//默认初始值为0

    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }

    public void setAtomicInteger() {
//        atomicInteger.getAndIncrement();
        atomicInteger.incrementAndGet();
    }

    public static void main(String[] args) throws InterruptedException {
        CASDemo2 demo2 = new CASDemo2();
        CountDownLatch countDownLatch = new CountDownLatch(100);
        for (int i = 1; i <= 100; i++) {
             new Thread(() -> {
                 for (int j = 0; j < 100; j++) {
                    demo2.setNumber();
                     demo2.setAtomicInteger();
                 }
                 //执行一个线程就减一
                 countDownLatch.countDown();
                     }, String.valueOf(i)).start();
        }
        //线程睡眠几秒
//        try {
//            TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {throw new RuntimeException(e);}
        countDownLatch.await();
        System.out.println("V1最后的number值为："+demo2.getNumber());
        System.out.println("V2最后的number值为："+demo2.getAtomicInteger().get());
    }
}
